from flask import request, current_app
from flask_jwt_extended import jwt_required
from . import permission_bp
from ..services.permission_service import PermissionService
from ..utils.response import success_response, error_response
from ..middlewares.permission import check_permission

@permission_bp.route('', methods=['GET'])
@jwt_required()
@check_permission()
def get_permissions():
    """获取权限列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('size', 10, type=int)
        keyword = request.args.get('keyword', None, type=str)
        
        result = PermissionService.get_permission_list(
            page=page, per_page=per_page, keyword=keyword
        )
        return success_response(data=result)
    except Exception as e:
        current_app.logger.error(f"获取权限列表失败: {str(e)}")
        return error_response(message="获取权限列表失败")

@permission_bp.route('/tree', methods=['GET'])
@jwt_required()
@check_permission()
def get_permission_tree():
    """获取权限树"""
    try:
        result = PermissionService.get_permission_tree()
        return success_response(data=result)
    except Exception as e:
        current_app.logger.error(f"获取权限树失败: {str(e)}")
        return error_response(message="获取权限树失败")

@permission_bp.route('', methods=['POST'])
@jwt_required()
@check_permission()
def create_permission():
    """创建权限"""
    try:
        data = request.get_json()
        if not data or not data.get('permission_name') or not data.get('permission_code'):
            return error_response(message="权限名称和权限代码不能为空")
        
        if not data.get('resource_type'):
            return error_response(message="资源类型不能为空")
        
        # 检查权限代码是否已存在
        if PermissionService.get_permission_by_code(data['permission_code']):
            return error_response(message="权限代码已存在")
        
        # 如果有父权限ID，检查父权限是否存在
        if data.get('parent_id'):
            parent = PermissionService.get_permission_by_id(data['parent_id'])
            if not parent:
                return error_response(message="父权限不存在", code=404)
        
        permission = PermissionService.create_permission(data)
        return success_response(message="创建成功", data=permission.to_dict())
    except Exception as e:
        current_app.logger.error(f"创建权限失败: {str(e)}")
        return error_response(message="创建权限失败")

@permission_bp.route('/<int:id>', methods=['GET'])
@jwt_required()
@check_permission()
def get_permission(id):
    """获取指定权限详情"""
    try:
        permission = PermissionService.get_permission_by_id(id)
        if not permission:
            return error_response(message="权限不存在", code=404)
        return success_response(data=permission.to_dict())
    except Exception as e:
        current_app.logger.error(f"获取权限详情失败: {str(e)}")
        return error_response(message="获取权限详情失败")

@permission_bp.route('/<int:id>', methods=['PUT'])
@jwt_required()
@check_permission()
def update_permission(id):
    """更新权限信息"""
    try:
        permission = PermissionService.get_permission_by_id(id)
        if not permission:
            return error_response(message="权限不存在", code=404)
        
        data = request.get_json()
        if not data:
            return error_response(message="更新数据不能为空")
        
        # 如果更新权限代码，需要检查是否已存在
        if 'permission_code' in data and data['permission_code'] != permission.permission_code:
            if PermissionService.get_permission_by_code(data['permission_code']):
                return error_response(message="权限代码已存在")
        
        # 如果更新父权限ID，检查父权限是否存在
        if 'parent_id' in data and data['parent_id']:
            parent = PermissionService.get_permission_by_id(data['parent_id'])
            if not parent:
                return error_response(message="父权限不存在", code=404)
            # 检查是否形成循环引用
            if data['parent_id'] == id:
                return error_response(message="不能将自己设为父权限")
        
        permission = PermissionService.update_permission(permission, data)
        return success_response(message="更新成功", data=permission.to_dict())
    except Exception as e:
        current_app.logger.error(f"更新权限信息失败: {str(e)}")
        return error_response(message="更新权限信息失败")

@permission_bp.route('/<int:id>', methods=['DELETE'])
@jwt_required()
@check_permission()
def delete_permission(id):
    """删除权限"""
    try:
        permission = PermissionService.get_permission_by_id(id)
        if not permission:
            return error_response(message="权限不存在", code=404)
        
        try:
            PermissionService.delete_permission(permission)
            return success_response(message="删除成功")
        except ValueError as e:
            return error_response(message=str(e))
    except Exception as e:
        current_app.logger.error(f"删除权限失败: {str(e)}")
        return error_response(message="删除权限失败")

@permission_bp.route('/<int:id>/status', methods=['PATCH'])
@jwt_required()
@check_permission()
def update_permission_status(id):
    """修改权限状态"""
    try:
        permission = PermissionService.get_permission_by_id(id)
        if not permission:
            return error_response(message="权限不存在", code=404)
        
        data = request.get_json()
        if 'status' not in data:
            return error_response(message="状态参数不能为空")
        
        permission = PermissionService.update_permission_status(permission, data['status'])
        return success_response(message="状态更新成功", data={"status": permission.status})
    except Exception as e:
        current_app.logger.error(f"更新权限状态失败: {str(e)}")
        return error_response(message="更新权限状态失败")

@permission_bp.route('/batch', methods=['POST'])
@jwt_required()
@check_permission()
def batch_create_permissions():
    """批量创建权限"""
    try:
        data = request.get_json()
        if not data or not isinstance(data.get('permissions'), list):
            return error_response(message="权限列表不能为空")
        
        # 验证每个权限的必要字段
        for permission_data in data['permissions']:
            if not permission_data.get('permission_name') or not permission_data.get('permission_code'):
                return error_response(message="权限名称和权限代码不能为空")
            if not permission_data.get('resource_type'):
                return error_response(message="资源类型不能为空")
            
            # 检查权限代码是否已存在
            if PermissionService.get_permission_by_code(permission_data['permission_code']):
                return error_response(message=f"权限代码 {permission_data['permission_code']} 已存在")
        
        # 批量创建权限
        created_permissions = []
        for permission_data in data['permissions']:
            permission = PermissionService.create_permission(permission_data)
            created_permissions.append(permission.to_dict())
        
        return success_response(
            message="批量创建成功", 
            data=created_permissions
        )
    except Exception as e:
        current_app.logger.error(f"批量创建权限失败: {str(e)}")
        return error_response(message="批量创建权限失败") 